<?php

require_once 'Vega/Module.php';
require_once 'Vega/Language.php';

class Mobitv_Admin_Action extends Vega_Module {

    protected $_config = null;
    protected $_module = null;
    protected $_action = null;
    protected $_actionId = null;
    protected $_language = null;
    protected $_langData = array();
    protected $_validator = null;

    public function __construct(Vega_App $app) {
        parent::__construct($app);

        // Get core config
        $dbConfig = array();
        Vega_App::getInstance()->coreConfig = array_merge(Vega_App::getInstance()->coreConfig, $dbConfig);
        $this->_config = Vega_App::getInstance()->coreConfig;
        // Check cookie
        $this->autoLogin();        

        $this->_view->loadHelper('common');

        // Get action Id
        $r = $this->_request;
        $this->_module = $r->getModuleName();
        $this->_action = $r->getModuleName() . '/' . $r->getActionName();
        $this->_actionId = $r->getModuleName() . ':' . $r->getActionName();
    }

    /**
     * Return 'execute', which is the action method
     *
     * @param string $action
     * @return string
     */
    public function _getActionMethod($action) {
        return 'execute';
    }

    public function preRenderOutput() {
        $this->_view->assign('_module', $this->_module);
        $this->_view->assign('_action', $this->_action);
        $this->_view->assign('_actionId', $this->_actionId);
    }

    public function getActionId() {
        return $this->_actionId;
    }

    public function buildValidator($rules = array()) {
        require_once 'Vega/Validation.php';

        if (!class_exists('Vega_Validation')) {
            require_once 'Vega/Exception.php';

            throw new Vega_Exception('{' . __CLASS__ . '} Unable to load class: Vega_Validator');
        } else {
            if ($rules) {
                $this->_validator = new Vega_Validation($rules);
            } else {
                $this->_validator = new Vega_Validation();
            }

            $this->_validator->setInstance($this);
        }

        return $this->_validator;
    }

    public function requireLogin() {
        if (!isset($_SESSION['username'])) {
            $urlParam = ($_SERVER['REQUEST_URI'] != '/') ? '?ref=' . base64_encode($_SERVER['REQUEST_URI']) : '';
            header('location: /admin/login' . $urlParam);
            die;
        }
    }

    public function autoLogin() {
        if (!isset($_SESSION['userid'])) {
            if (isset($_COOKIE['userid'])) {
                $userId = isset($_COOKIE['userid']) ? $_COOKIE['userid'] : '';
                $userName = isset($_COOKIE['username']) ? $_COOKIE['username'] : '';
                $userHash = isset($_COOKIE['userhash']) ? $_COOKIE['userhash'] : '';

                if ($userHash == md5($userId . $userName . 'Mobitv')) {
                    // Valid cookie
                    $_SESSION['userid'] = $userId;
                    $_SESSION['username'] = $userName;
                }
            }
        }
    }

    public function checkPermission() {
        $this->requireLogin();
        $userDao = Vega_Dao::factory('Mobitv_Admin_Admin');
        $userId = $_SESSION['userid'];
        $perm = $userDao->getPermission($userId, $this->_actionId);

        $perm['group_permission'] = is_null($perm['group_permission']) ? 0 : $perm['group_permission'];
        $allow = is_null($perm['user_permission']) ? $perm['group_permission'] : $perm['user_permission'];
        if (!$allow)
            $this->forward401();
        /*
          $check = 0;
          for($i =0; $i < sizeof($perm); $i ++){
          if($perm[$i]['group_permission'] == 1 || !is_null($perm[$i]['user_permission'])){
          $check ++;
          }
          }
          if($check == 0)
          $this->forward401();
         */
    }

    public function forward404() {
        throw new Exception('', 404);
    }

    public function forward401() {
        throw new Exception('', 401);
    }

    public function alert($msg) {
        if ($msg)
            $_SESSION['msg'] = $msg;
    }

    public function gotoUrl($url, $msg=null) {
        if ($msg)
            $_SESSION['msg'] = $msg;
        $this->redirect($url);
    }

    private function arrayToXml($series, $graphs) {
        $return = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        $return .= "<chart>";
        if ($series && $graphs) {
            $return .= "<series>";
            $i = 0;
            foreach ($series AS $item) {
                $return .= "<value xid=\"$i\">$item</value>";
                $i++;
            }
            $return .= "</series>";

            $return .= "<graphs>";

            $gid = 1;
            foreach ($graphs AS $graph) {
                $return .= "<graph gid=\"$gid\">";
                $i = 0;
                foreach ($graph AS $item) {
                    $return .= "<value xid=\"$i\">$item</value>";
                    $i++;
                }
                $return .= "</graph>";
                $gid++;
            }

            $return .= "</graphs>";
        }
        $return .= "</chart>";

        return $return;
    }

    public function updateLogAdmin($admin_id, $object, $object_id, $action) {
        $userDao = Vega_Dao::factory('Mobitv_Admin_Admin');
        $userDao->updateLogAdmin($admin_id, $object, $object_id, $action);
    }

    public function updateLoginStatus() {
        $userDao = Vega_Dao::factory('Mobitv_Admin_Admin');
        if (!isset($_SESSION['admin_time_out'])) {
            $_SESSION['admin_time_out'] = time();
        } else {
            if (time() - $_SESSION['admin_time_out'] > $this->_config['admin_session']['session_timeout']) {
                $this->gotoUrl('/admin/logout');
            } else {
                $_SESSION['admin_time_out'] = time();
                $userDao->updateLoginStatus();
            }
        }
    }

}